const mysql = require('../../core/mysql');

const log = require('../../core/logger').getLogger("system");
const moment = require('moment');
const common = require('../../core/common');
const stringUtils = require('../../core/util/StringUtils');
const assign = require('lodash/assign');

exports.add = async(ctx) => {
    let house_name = ctx.request.body.house_name ?  ctx.request.body.house_name.trim() : '';
    let house_create_time =  moment().format('YYYY-MM-DD HH:mm:ss');
    let house_update_time =  moment().format('YYYY-MM-DD HH:mm:ss');
    let house_type_id = ctx.request.body.house_type_id || 0;
    let building_id = ctx.request.body.building_id || 0;
    let floor = ctx.request.body.floor || 0;
    let house_id = ctx.request.body.house_id || 0;
    //新建 非独立展示间的 样板房时 需传入 已有的houseid 进行 update
    let unit = ctx.request.body.unit || 0;
    let household_num = ctx.request.body.household_num || 0;
    let status = ctx.request.body.status || 0;
    let is_model_house = ctx.request.body.is_model_house || 0;
    //0:普通房 1:样板房
    let model_house_location = ctx.request.body.model_house_location || 0;

    let newhouse = {
        house_name,
        house_create_time,
        house_update_time,
        house_type_id,
        building_id,
        floor,
        unit,
        household_num,
        status,
        is_model_house,
        model_house_location,
    };
    try{
        let parseInt_is_model_house = parseInt(is_model_house, 10);
        let parseInt_model_house_location = parseInt(model_house_location, 10);

        if(building_id && building_id > 0) {
            let existRows1 = await mysql.query(`SELECT * FROM building WHERE building_id = ?`, building_id);
            if (existRows1.length <= 0){
                ctx.body = {
                    result: 201,
                    message: "找不到对应楼幢"
                };
                return
            }
        }

        if((parseInt_is_model_house && !parseInt_model_house_location )|| !parseInt_is_model_house) {
            if (house_name === '' || parseInt(house_type_id) <= 0  || parseInt_is_model_house === '') {
                ctx.body = {
                    result: 201,
                    message: "请重新检查参数"
                };
                return;
            }
            let existRows = await mysql.query(`SELECT * FROM house_type WHERE house_type_id = ?`, house_type_id);
            if (existRows.length <= 0) {
                ctx.body = {
                    result: 201,
                    message: "找不到对应户型"
                };
                return
            }
            if (parseInt_is_model_house === 1){
                let selectModelHouses = await mysql.query(`select house_id from v_house_detail where house_name = ? and project_id = ? and is_model_house = 1 `,
                    [house_name,existRows[0].project_id]);
                if (selectModelHouses.length > 0){
                    ctx.body = {
                        result: 203,
                        message: "已存在此样板房"
                    };
                    return;
                }
            }
            let ret = await mysql.query(`INSERT INTO house SET ?`, newhouse);
            if (!ret || ret.insertId === -1){
                ctx.body = {
                    result: 202,
                    message: "新增失败"
                };
            } else {
                ctx.body = {
                    result: 200,
                    id: ret.insertId,
                    message: "新增成功"
                };
            }
        }
        else{
            if (parseInt(house_id) <= 0 || house_name === '') {
                ctx.body = {
                    result: 201,
                    message: "请检查参数"
                };
                return;
            }
            if (parseInt(house_type_id) !== 0){
                ctx.body = {
                    result: 203,
                    message: "更新已有房屋为样板房，请勿传入户型"
                };
                return;
            }
            let selectRows = await mysql.query(`SELECT house_name,is_model_house,project_id FROM v_house_detail WHERE house_id = ?`, house_id);
            if (selectRows.length > 0) {
                let selectExistHouses = await mysql.query(`SELECT house_id FROM v_house_detail WHERE house_id <> ? and house_name = ? and project_id = ? and is_model_house = 1 `,
                    [house_id,house_name,selectRows[0].project_id]);
                if (selectExistHouses.length > 0){
                    ctx.body = {
                        result: 203,
                        message: "已存在此样板房"
                    };
                    return;
                }
                let update_data = assign({}, selectRows[0],ctx.request.body)
                delete update_data.project_id;
                ret = await mysql.query(`UPDATE house SET ? WHERE house_id= ? `, [update_data,house_id]);
                if (!ret || ret.insertId === -1) {
                    ctx.body = {
                        result: 204,
                        message: "更新失败"
                    };
                } else {
                    ctx.body = {
                        result: 200,
                        message: "增加样板房成功"
                    };
                }
            } else {
                ctx.body = {
                    result: 203,
                    message: "对象不存在或者已删除"
                };
            }
        }



    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误"+e.toString()
        };
    }
}

exports.delete = async(ctx) => {
    let house_id = ctx.params.house_id || 0;
    if (house_id <= 0) {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return
    }
    try{
        let selectHouse = await mysql.query(`select * from house WHERE house_id = ?`, house_id);
        if (selectHouse.length <= 0){
            ctx.body = {
                result: 202,
                message: "请检查参数"
            };
            return
        } 
        if (selectHouse[0].is_model_house === 1 && selectHouse[0].model_house_location === 1){
            selectHouse[0].is_model_house = 0;
            selectHouse[0].model_house_location = 0;
            selectHouse[0].house_update_time = moment().format('YYYY-MM-DD HH:mm:ss');
            let ret = await mysql.query(`update house set ? WHERE house_id = ?`, [selectHouse[0],house_id]);
            if (!ret || ret.affectedRows <= 0){
                ctx.body = {
                    result: 203,
                    message: "删除样板房失败"
                };
            } else {
                ctx.body = {
                    result: 200,
                    message: "删除样板房成功"
                };
            }
        } else{
            let ret = await mysql.query(`delete from house WHERE house_id = ?`, house_id);
            if (!ret || ret.affectedRows <= 0){
                ctx.body = {
                    result: 203,
                    message: "删除失败"
                };
            } else {
                ctx.body = {
                    result: 200,
                    message: "删除成功"
                };
            }
        }
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误"+e.toString()
        };
    }
}

exports.update = async(ctx) => {
    let request_body = ctx.request.body;
    let house_id = request_body.house_id || 0;
    let house_name = request_body.house_name ?  request_body.house_name.trim() :  '';
    let is_model_house = request_body.is_model_house || 2;
    let house_type_id = request_body.house_type_id || '';

    if (house_id <= 0 || house_name === '' || is_model_house === 2) {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
    }else{
        try {
            let existHouseType = await mysql.query(`SELECT * FROM house_type WHERE house_type_id = ?`, house_type_id);
            if (existHouseType.length <= 0) {
                ctx.body = {
                    result: 202,
                    message: "找不到对应户型"
                };
                return
            }
            let selectRows = await mysql.query(`SELECT * FROM house WHERE house_id = ?`, house_id);
            if (selectRows.length > 0) {
                // let update_data = assign({}, selectRows[0],ctx.request.body);
                if (parseInt(is_model_house) === 1){
                    let selectModelHouses = await mysql.query(`select house_id from v_house_detail where house_name = ? and project_id = ? and house_id <> ? and is_model_house = 1 `,
                        [house_name,existHouseType[0].project_id,house_id]);
                    if (selectModelHouses.length > 0){
                        ctx.body = {
                            result: 202,
                            message: "已存在此样板房"
                        };
                        return;
                    }
                }
                ret = (house_type_id !== '') ?
                    await mysql.query(`UPDATE house SET house_name = '${house_name}', is_model_house = ${is_model_house}, house_type_id=${house_type_id}  WHERE house_id= ${house_id} `)
                    : await mysql.query(`UPDATE house SET house_name = '${house_name}', is_model_house = ${is_model_house} WHERE house_id= ${house_id} `);
                if (!ret || ret.affectedRows === 0) {
                    ctx.body = {
                        result: 203,
                        message: "更新失败"
                    };
                } else {
                    ctx.body = {
                        result: 200,
                        message: "更新成功"
                    };
                }
            } else {
                ctx.body = {
                    result: 204,
                    message: "对象不存在或者已删除"
                };
            }
        }catch (e) {
            ctx.body = {
                result: 205,
                message: "错误"+e.toString()
            };
        }
    }
}


exports.getList = async(ctx) => {
    let create_user_id = ctx.user.id || '';
    let project_id = ctx.query.project_id;
    let is_model_house = ctx.query.is_model_house || -1;
    let building_id = ctx.query.building_id;
    let counts = ctx.query.counts || 10;
    let indexfrom = ctx.query.indexfrom || 0;

    if (create_user_id === ''){
        ctx.body = {
            result: 201,
            message: "无效的用户id"
        };
    } else {
        try {
            let parseInt_is_model_house = parseInt(is_model_house, 10);
            let sqlmodelhouse = '';
            if (parseInt_is_model_house === 0) {
                sqlmodelhouse += ` and is_model_house = ${parseInt_is_model_house} `;
            }else if (parseInt_is_model_house === 1) {
                sqlmodelhouse += ` and is_model_house = ${parseInt_is_model_house} `;
            }
            if (project_id) {
                let existRows = await mysql.query(`SELECT * FROM project WHERE project_id = ?`, project_id);
                if (existRows.length <= 0){
                    ctx.body = {
                        result: 204,
                        message: "找不到对应项目"
                    };
                    return
                }
                let results = await mysql.query(`SELECT * FROM v_house_detail where project_id =${project_id} ${sqlmodelhouse} ORDER BY house_id LIMIT ${indexfrom}, ${counts} `);
                let totalResult = await mysql.query(`SELECT COUNT(house_id) AS total FROM v_house_detail where project_id =${project_id} ${sqlmodelhouse} `);
                ctx.body = {
                    result: 200,
                    list:results,
                    totalpage:Math.ceil((totalResult.length > 0 ? totalResult[0].total : 0)/counts),
                    totalcounts:totalResult.length > 0 ? totalResult[0].total : 0,
                    message: "查询该项目对应房屋成功"
                };
            } else if (building_id) {
                let existRows1 = await mysql.query(`SELECT * FROM building WHERE building_id = ?`, building_id);
                if (existRows1.length <= 0){
                    ctx.body = {
                        result: 204,
                        message: "找不到对应楼幢"
                    };
                    return
                }
                let results = await mysql.query(`SELECT * FROM v_house_detail where building_id =${building_id} ${sqlmodelhouse}ORDER BY house_id LIMIT ${indexfrom}, ${counts} `);
                let totalResult = await mysql.query(`SELECT COUNT(house_id) AS total FROM v_house_detail where building_id =${building_id} ${sqlmodelhouse} `);
                ctx.body = {
                    result: 200,
                    list:results,
                    totalpage:Math.ceil((totalResult.length > 0 ? totalResult[0].total : 0)/counts),
                    totalcounts:totalResult.length > 0 ? totalResult[0].total : 0,
                    message: "查询该楼幢对应房屋成功"
                };
            }else {
                //查询所有的 house list 进行展示
                let results = await mysql.query(`SELECT * FROM v_house_detail where building_id is not null ${sqlmodelhouse} ORDER BY house_id LIMIT ${indexfrom}, ${counts} `);
                let totalResult = await mysql.query(`SELECT COUNT(house_id) AS total FROM v_house_detail where building_id is not null ${sqlmodelhouse} `);
                ctx.body = {
                    result: 200,
                    list:results,
                    totalpage:Math.ceil((totalResult.length > 0 ? totalResult[0].total : 0)/counts),
                    totalcounts:totalResult.length > 0 ? totalResult[0].total : 0,
                    message: "查询成功"
                };
            }
        }catch (e) {
            ctx.body = {
                result: 205,
                message: "错误" + e.toString()
            };
        }
    }
}

exports.getDetail = async(ctx)=>{
    let houseId = ctx.params.house_id;
    if (!houseId ){
        ctx.body = {
            result: 201,
            message: "请携带houseid"
        };
    }
    try {
        let house = await mysql.query(`SELECT * FROM v_house_detail  where house_id = ${houseId}`);
        let houseResult = house && house[0];
        let house_type_id = houseResult.house_type_id;
        houseResult.scenario_list = await mysql.query(`SELECT * FROM scenario where house_type_id = ${house_type_id} and is_deleted = 0 `);
        for (let scenario of Object.values(houseResult.scenario_list)) {
            let scenarioDevices = await mysql.query(`SELECT * FROM t_scenario_v_device WHERE scenario_id = ${scenario.scenario_id} ` );
            scenario.triggering_condition = [];
            scenario.matching_condition = [];
            scenario.action = [];
            for (let scenarioDevice of Object.values(scenarioDevices)) {
                if (scenarioDevice.type === 0){
                    scenario.triggering_condition.push(scenarioDevice);
                } else if(scenarioDevice.type === 1){
                    scenario.matching_condition.push(scenarioDevice);
                }else{
                    scenario.action.push(scenarioDevice);
                }
            }
        }
        houseResult.room_list = await mysql.query(`SELECT * FROM room where house_type_id = ${house_type_id}`);
        for(let i = 0; i < houseResult.room_list.length; i++) {
            houseResult.room_list[i].room_product_list = await mysql.query(`SELECT * FROM v_temp_device_detail where room_id = ${houseResult.room_list[i].room_id}`);
        }
        ctx.body = {
            result: 200,
            results: houseResult,
            message: "返回成功"
        };
    } catch (e) {
        ctx.body = {
            result: 205,
            message: "错误 " + e.toString()
        };
    }
}